package com.dchh.android.suverynew.act;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.dchh.android.suverynew.R;
import com.dchh.android.suverynew.adapter.CycleListAdapter;
import com.dchh.android.suverynew.base.SBaseActivity;
import com.dchh.android.suverynew.common.SPreferencesManager;
import com.dchh.android.suverynew.presenter.ITableSelectPresenter;
import com.dchh.android.suverynew.presenter.impl.TableSelectPresenter;
import com.dchh.android.suverynew.view.ITaleSelectView;
import com.dhcc.android.base.base.MSApplication;
import com.dhcc.android.base.common.bean.Table;
import com.dhcc.android.base.db.DBManagerUtil;
import com.dhcc.android.base.utils.CommenUtil;
import com.dhcc.android.base.utils.Constants;
import com.dhcc.android.base.utils.FileUtil;
import com.dhcc.android.base.utils.StringUtil;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * 表选择
 *
 * @author zhoudan
 * @date 2015年5月19日
 */
public class TableSelectActivity extends SBaseActivity implements ITaleSelectView {

    public static final String MJDC_CODE = "002,003,004,007";
    public static final String CLDC_CODE = "005,006,008";

    /**
     * 农作物预计产量调查表
     */
    public static final String ycdc = "204";
    /**
     * 踏田估产调查表
     */
    public static final String gcdc = "205";
    /**
     * 农产量抽样调查放样实测作物调查表
     */
    public static final String sgsc = "206";
    /**
     * 显示列表的ListView
     */
    private ListView listview;
    /**
     * 列表适配器
     */
    private CycleListAdapter adapter;
    /**
     * raw中的表集合
     */
    private List<Table> tlist;

    private String root;

    private String periodCode, periodLabel;
    private String taskName;

    private ITableSelectPresenter mTableSelectPresenter = new TableSelectPresenter(this);

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.task_cycle_select);
    }

    @Override
    protected void setTitle(TextView toolbar_title) {
        toolbar_title.setText("表选择");
    }

    /**
     * 初始化控件
     */

    @Override
    public void initView() {
        periodCode = getIntent().getStringExtra("periodCode");
        periodLabel = getIntent().getStringExtra("periodLabel");
        taskName = getIntent().getStringExtra("taskName");
        LinearLayout notelayout = (LinearLayout) findViewById(R.id.note_layout);
        TextView note = (TextView) findViewById(R.id.note);
        notelayout.setVisibility(View.VISIBLE);
        note.setText(getIntent().getStringExtra("periodLabel"));
        listview = (ListView) findViewById(R.id.cycle_listview);
        // 1.解析config.xml
        InputStream is = this.getResources().openRawResource(R.raw.tablestyle);
        root = SPreferencesManager.getValue(MSApplication.TASK_SAVE_PATH, FileUtil.getSavePath());
        mTableSelectPresenter.initData(is, periodCode);
        listview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (StringUtil.isFastDoubleClick(500)) {
                    return;
                }
                Map<String, String> item = (Map<String, String>) parent.getAdapter().getItem(position);
                //判断是面积调查还是产量调查
                if (MJDC_CODE.contains(periodCode)) { //面积调查
                    Table tb = new Table();
                    tb.setCode(item.get("id"));
                    tb.setLabel(item.get("name"));
                    Constants.currentTable = tb;
                    mTableSelectPresenter.getNodeList(root, item.get("id"));
                } else if (CLDC_CODE.contains(periodCode)) { //产量调查
                    // 判断是产量调查的哪一个表
                    String tid = item.get("id");
                    if (ycdc.equals(tid)) {//预产
                        initYCDatas(item.get("id"), item.get("name"));// 提前数据
                    } else {
                        Table tb = new Table();
                        tb.setCode(item.get("id"));
                        tb.setLabel(item.get("name"));
                        Constants.currentTable = tb;
                        mTableSelectPresenter.getNodeList(root, tid);
                    }
                }
            }
        });
        // 恢复异常关闭
        this.mTableSelectPresenter.restore();
    }

    private Class<?> getIntentClass(String tableid) {
        if (tableid.equals(ycdc)) {
            return YCMapSelectActivity.class;
        } else if (tableid.equals(gcdc)) {
            return GCZwSelectActivity.class;
        } else if (tableid.equals(sgsc)) {
            return SGSCZwSelectActivity.class;
        } else {
            return MapSelectActivity.class;
        }
    }

    /**
     * 提取面积调查数据 --预产
     */
    private void initYCDatas(final String tbid, final String tblabel) {
        // 判断是否已经提取数据
        String yc_dbpath = root + "/" + Constants.currentTask.getTitle() + "/TASK/YIELD/DATA.db";
        String mj_dbpath = root + "/" + Constants.currentTask.getTitle() + "/TASK/TRANSPORT/DATA.db";
        DBManagerUtil yc_dbutil = DBManagerUtil.getInstance(yc_dbpath, this);
        int count = yc_dbutil.getCount(yc_dbpath, "预产表", null, null);
        if (count > 0) {
            gotoYCMapSeleteActivity(tbid, tblabel);
        } else {
            Constants.showDialog(this, "正在提取面积调查数据，请稍候...");
            DBManagerUtil mj_dbutil = DBManagerUtil.getInstance(mj_dbpath, this);
            String zwtable = "作物" + Constants.currentTask.getRefrence();
            String sstable = "设施" + Constants.currentTask.getRefrence();
            List<Map<String, String>> list = mj_dbutil.getResearchDatas(zwtable, sstable, mj_dbpath);
            if (list != null && list.size() > 0) {
                System.out.println("-预产-面积调查数据--：" + list.size());
                yc_dbutil.saveResearchDatasFORYC(periodLabel, tblabel, list, "预产表", yc_dbpath);
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        Constants.closeDialog();
                        gotoYCMapSeleteActivity(tbid, tblabel);
                    }
                }, 2000);
            } else {
                Constants.closeDialog();
                CommenUtil.toast("提取到的面积调查数据为空", this);
            }
        }
    }

    /**
     * 进入预产层级选择页面
     */
    private void gotoYCMapSeleteActivity(String tbid, String tblabel) {
        Table tb = new Table();
        tb.setCode(tbid);
        tb.setLabel(tblabel);
        Constants.currentTable = tb;
        mTableSelectPresenter.getNodeList(root, "ycdc");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (MJDC_CODE.contains(periodCode)) {
            getMenuInflater().inflate(R.menu.table_select_menu, menu);
        }

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.tuzhi:
                this.mTableSelectPresenter.getNodeList(root, null);
                Intent intent = new Intent(TableSelectActivity.this, PKGPhotoActivity.class);
                intent.putExtra("period", periodLabel);
                intent.putExtra("taskName", taskName);
                startActivity(intent);
                break;

        }
        return true;
    }

    @Override
    public void onInitData(List<Map<String, String>> list) {
        if (adapter == null) {
            adapter = new CycleListAdapter(this, list);
        }
        listview.setAdapter(adapter);
    }

    @Override
    public void onRestore(Table table) {
        Constants.currentTable = table;
    }

    @Override
    public void onNodeList(String code) {
        if (code != null) {
            //判断是面积调查还是产量调查
            if (MJDC_CODE.contains(periodCode)) { //面积调查
                Intent intent = new Intent();
                intent.setClass(TableSelectActivity.this, MapSelectActivity.class);
                intent.putExtra("taskName", taskName);
                intent.putExtra("periodCode", periodCode);
                intent.putExtra("periodLabel", periodLabel);
                startActivity(intent);
            } else if (CLDC_CODE.contains(periodCode)) { //产量调查
                // 判断是产量调查的哪一个表
                if (!ycdc.equals(code)) {//预产
                    Class<?> cls = getIntentClass(code);
                    Intent intent = new Intent();
                    intent.setClass(TableSelectActivity.this, cls);
                    intent.putExtra("taskName", taskName);
                    startActivity(intent);
                }
            }else if("ycdc".equals(periodCode)) {
                Class<?> cls = getIntentClass(code);
                Intent intent = new Intent();
                intent.setClass(TableSelectActivity.this, cls);
                intent.putExtra("taskName", taskName);
                intent.putExtra("periodCode", periodCode);
                intent.putExtra("periodLabel", periodLabel);
                startActivity(intent);
            }
        }
    }

    @Override
    public void onYCDataSearching() {
        Constants.showDialog(this, "正在提取面积调查数据，请稍候...");
    }

    @Override
    public void onYCData(final String tid, final String tblabel) {
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                gotoYCMapSeleteActivity(tid, tblabel);
            }
        }, 2000);
    }

    @Override
    public void onYCDataEmpty() {
        CommenUtil.toast("提取到的面积调查数据为空", this);
    }
}
